package com.nsgf.library.ui.page.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.MessageBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.repository.DataRepository;
import com.nsgf.library.data.response.DataResult;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.FragmentNsgfHomeMessageBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.event.EventMsg;
import com.nsgf.library.event.RxBus;
import com.nsgf.library.ui.adapter.PlaylistAdapter;
import com.nsgf.library.ui.page.BaseFragment;
import com.nsgf.library.ui.page.MessageReginDetailsActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.skjz.utils.ToastUtils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.disposables.Disposable;

public class HomeMessageFragment extends BaseFragment {

    private MineFragmentStates mStates;
    private FragmentNsgfHomeMessageBinding mBinding;
    private AccountRequester mAccountRequester;

    private PlaylistAdapter mAdapter;

    private int number = 0;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(MineFragmentStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new PlaylistAdapter(getContext());
        return new DataBindingConfig(R.layout.fragment_nsgf_home_message, BR.vm, mStates).addBindingParam(BR.click, new ClickProxy()).addBindingParam(BR.adapter, mAdapter);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mBinding = (FragmentNsgfHomeMessageBinding) getBinding();
        getLifecycle().addObserver(mAccountRequester);
        mBinding.titlebar.titleBarBack.setVisibility(View.GONE);
        mBinding.titlebar.titleBarClear.setVisibility(View.VISIBLE);
        mBinding.titlebar.titleBarClear.setOnClickListener(this::onClick);
        mStates.titleBar.set("消息推送");

        mBinding.smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getDatas(search);
            }
        });
        mBinding.smartRefreshLayout.autoRefresh();


        mAdapter.setOnItemClickListener((viewId, item, position) -> {

            mAdapter.getCurrentList().get(position).setIsRead(1);
            mAdapter.notifyItemChanged(position);
            Intent intent = new Intent(getActivity(), MessageReginDetailsActivity.class);
            intent.putExtra("title", item.getTypeName());
            intent.putExtra("id", item.getId());
            startActivity(intent);

            number = 0;
            for (MessageBean.DataBean messageBean : mAdapter.getCurrentList()) {

                if (0 == messageBean.getIsRead()) {
                    number++;
                }
            }
            EventMsg eventMsg = new EventMsg();
            eventMsg.setMsg("message");
            eventMsg.setContent(String.valueOf(number));
            RxBus.get().post(eventMsg);
            EventBus.getDefault().post(eventMsg);
        });


        mAccountRequester.getSrc().observe(this, new Observer<DataResult<ResponseStatus<String>>>() {
            @Override
            public void onChanged(DataResult<ResponseStatus<String>> responseStatusDataResult) {

                if (responseStatusDataResult.getResponseStatus().isSuccess()) {
                    if (responseStatusDataResult.getResult().getResponseCode() == 200) {

                        for (MessageBean.DataBean bean : mAdapter.getCurrentList()) {

                            bean.setIsRead(1);

                        }
                        EventMsg eventMsg = new EventMsg();
                        eventMsg.setMsg("message");
                        eventMsg.setContent("0");
                        RxBus.get().post(eventMsg);
                        EventBus.getDefault().post(eventMsg);

                    } else {
                        ToastUtils.showLongToast(responseStatusDataResult.getResult().getMsg());
                    }
                }
            }
        });

    }

    public static class MineFragmentStates extends StateHolder {

        public final State<String> name = new State<>("");

        public final State<Boolean> loadingVisible = new State<>(false);

    }


    public class ClickProxy {

        public void clear() {
            mAccountRequester.setClearMessage(2, null);
        }

        public void search() {
            getDatas(mStates.searchContent.get());
        }
    }


    private String search;

    /**
     * @param search
     */
    public void getDatas(String search) {
        this.search = search;
        DataRepository.getInstance().getMessage("message.type.2", search, null)
                .subscribe(new io.reactivex.Observer<DataResult<MessageBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(DataResult<MessageBean> dataResult) {
                        if (null != dataResult.getResult())
                            if (dataResult.getResult().getCode() == 200) {
                                mAdapter.submitList(dataResult.getResult().getData());

                                if (dataResult.getResult().getData().size() > 0) {
                                    mBinding.notdata.setVisibility(View.GONE);
                                } else {
                                    mBinding.notdata.setVisibility(View.VISIBLE);
                                }
                                number = 0;
                                for (MessageBean.DataBean messageBean : dataResult.getResult().getData()) {

                                    if (0 == messageBean.getIsRead()) {
                                        number++;
                                    }
                                }
                                EventMsg eventMsg = new EventMsg();
                                eventMsg.setMsg("message");
                                eventMsg.setContent(String.valueOf(number));
                                RxBus.get().post(eventMsg);
                                EventBus.getDefault().post(eventMsg);

                            } else {
                                if (401 == dataResult.getResult().getCode()) {
                                    UserInfo.getInstance().clearUserInfo();
                                }
                                ToastUtils.showLongToast(dataResult.getResult().getMsg());
                            }
                        else ToastUtils.showLongToast(dataResult.getResponseStatus().getMsg());
                        mBinding.smartRefreshLayout.finishRefresh();
                    }

                    @Override
                    public void onError(Throwable e) {

                        mBinding.smartRefreshLayout.finishRefresh();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if (id == R.id.title_bar_clear) {
            mAccountRequester.setClearMessage(2, null);
        }
    }
}
